#include "KeyCountServer.h"

namespace KeyCountServer {

Client::Client(Server *server, int clientId)
{
    m_server    = server;
    m_clientId  = clientId;
    m_stop      = 1;
    m_net       = new ClientNet(this, m_clientId);
    m_socket    = new Socket();
    m_thread    = new Thread();
}

Client::~Client()
{}

bool Client::start()
{
    m_net->m_msgGet = m_net->m_msgPut = NULL;
    m_thread->start(this, NULL);
    
    return 1;
}

void Client::run(Thread *thread, void *arg)
{
    Debug(("Client %d start", m_clientId));
    m_heartBeat = 0;
    m_stop = 0;
    while (1)
    {
        int rc = m_net->handle();
        if (m_net->m_msgGet != NULL)
        {
            Debug(("delete msgGet"));
            delete m_net->m_msgGet;
            m_net->m_msgGet = NULL;
            Debug(("deleted msgGet"));
        }
        if (m_net->m_msgPut != NULL)
        {
            Debug(("delete msgPut"));
            delete m_net->m_msgPut;
            m_net->m_msgPut = NULL;
            Debug(("deleted msgPut"));
        }
        if (rc == 0)
            break;
    }
    Debug(("close socket"));
    m_socket->close();
    m_stop = 1;
    pthread_detach(pthread_self());
    Debug(("Client %d stop", m_clientId));
}

bool Client::isStop()
{
    return m_stop;
}

}
